package com.xx.springboot.controller;

import com.xx.springboot.entity.ResponseBo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * @author xiaoxi
 * @description 文件上传类
 */
@RestController
@RequestMapping("/file")
public class FileUploadController {
    private static final Logger log = LoggerFactory.getLogger(FileUploadController.class);

    private static final String ROOT = "E:";

    private final ResourceLoader resourceLoader;

    public FileUploadController(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    /**
     * 上传文件接口
     * @param file
     * @return
     */
    @RequestMapping(value = "/uploadImage")
    public ResponseBo uploadImage(@RequestParam("image") MultipartFile file) {
        if(!file.isEmpty()){
            try {
                Files.copy(file.getInputStream(), Paths.get(ROOT, file.getOriginalFilename()));
                return ResponseBo.ok();
            } catch (IOException e) {
                e.printStackTrace();
                return ResponseBo.error(e.getLocalizedMessage());
            }
        }else {
            return ResponseBo.error();
        }
    }


}
